﻿using EA.BA;
using EA.Common;
using EA.DTO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EAClient
{
    public partial class DetailProduct : WebPage
    {
        override
        protected void Load(object sender, EventArgs e)
        {
            if(Request["id"]!=null && StringUtil.IsPositiveNumber(Request["id"])){
                int ID = Convert.ToInt32(Request["id"]);
                ProductImageBA productImageBA = new ProductImageBA();
                ProductBA productBA = new ProductBA ();
                ProductTO productTO = productBA.GetProductByID(ID);
                List<ProductImageTO> listProductImage = productImageBA.GetProductImageByProductID(ID);
                AuctionLogBA auctionLogBA = new AuctionLogBA();
                List<AuctionLogTO> listAuctionLog = auctionLogBA.GetAllAuctionLogByProductID(ID);
                LikeDislikeBA likeBA = new LikeDislikeBA();
                Boolean isLiked = true;
                Boolean isEndTime = true;
                int buyerId = auctionLogBA.GetEndBuyerId(ID);
                ProductTO productValidTO = productBA.GetValidAuctionProductByID(ID);
                if (productValidTO != null)
                {
                    isEndTime = false;
                }

                if (Session["USER_ID"]!=null)
                {
                    likeBA.isLiked((int)Session["USER_ID"], ID); 
                }
                CustomerBA customerBA = new CustomerBA();
                CustomerTO customer=customerBA.GetCustomerByID((int)Session["USER_ID"]);
                Attributes.Add("customer",customer);
                Attributes.Add("BuyerId", buyerId);
                Attributes.Add("productTO", productTO);
                Attributes.Add("listProductImage", listProductImage);
                Attributes.Add("listAuctionLog", listAuctionLog);
                Attributes.Add("isLiked", isLiked);
                Attributes.Add("isEndTime", isEndTime);
            }

        }

        public void Rating(HttpRequest Request, HttpResponse Response)
        {
            if (Request["ID"] == null || Request["ID"].Equals("") || !StringUtil.IsPositiveNumber(Request["ID"]) &&
                Request["rate"] == null || Request["rate"].Equals("") || !StringUtil.IsPositiveNumber(Request["rate"]))
            {
                Attributes.Add("error", "Information is invalid");
                this.isLoad = true;
                return;
            }
            int ID = Convert.ToInt32(Request["ID"]);
            int rate = Convert.ToInt32(Request["rate"]);
            ProductBA productBA = new ProductBA();
            productBA.UpdateRatingByID(ID, rate);
            this.isLoad = true;
        }

        public void UploadProduct(HttpRequest Request, HttpResponse Response)
        {
            int productCurrent = Convert.ToInt32(Request["product_current_id"]);
            if (Request["fprice"] == null || Request["fprice"] == "" || !StringUtil.IsNumeric(Request["fprice"])
                || (Request["sprice"] == null || Request["sprice"] == "" ||!StringUtil.IsNumeric(Request["sprice"]) ))
            {
                 Response.Redirect("/DetailProduct.aspx?id=" + productCurrent + "&error=Price is invalid");
                 return;
            }

            ProductTO productTO = new ProductTO();
            productTO.Name = Request["name"];
            productTO.Detail = Request["detail"];
            productTO.FloorPrice = Convert.ToInt32(Request["fprice"]);
            productTO.StepPrice = Convert.ToInt32(Request["sprice"]);
            productTO.SellerID = (int)Session["USER_ID"];
            productTO.Status = Constant.PRODUCT_PENDING_APPROVAL;
            ProductBA productBA = new ProductBA();
            
            int newId = productBA.GetLastestProduct();
            int index = 1;
            for (var i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i] != null)
                {
                    string standard = StringUtil.GetTimeSpan(DateTime.Now).ToString();
                    int contentLength = Request.Files[i].ContentLength;
                    string contentType = Request.Files[i].ContentType;
                    string fileName = Request.Files[i].FileName;
                    if (fileName != "")
                    {
                        fileName = fileName.Replace('.','_');
                    }

                    string ex = Path.GetExtension( Request.Files[i].FileName);
                    String path = Server.MapPath("~/" + WebPage.PATH_IMAGE);
                    Request.Files[i].SaveAs(path + fileName + standard + ex);
                    ProductImageTO productImageTO = new ProductImageTO();
                    productImageTO.URL = fileName + standard + ex;
                    productImageTO.ProductID =newId ;
                    productBA.InsertProductImage(productImageTO);
                    index++;
                }
            }

            if (productBA.InsertProduct(productTO))
            {
                Response.Redirect("/DetailProduct.aspx?id=" + productCurrent + "&msg=Product is waiting approve");
            }
            else
            {
                Response.Redirect("/DetailProduct.aspx?id=" + productCurrent + "&msg=Product can not be upload");
            }
        }

        public void Auction(HttpRequest Request, HttpResponse Response)
        {
            if (Request["price"] == null || Request["productId"] == null || !StringUtil.IsPositiveNumber(Request["productId"]) || !StringUtil.IsNumeric(Request["price"]))
            {
                Attributes.Add("error", "Information is invalid");
                this.isLoad = true;
                return;
            }

            Decimal price = Convert.ToDecimal(Request["price"]);
            int userId = (int)Session["USER_ID"];
            int productId = Convert.ToInt32(Request["productId"]);
            ProductBA productBA = new ProductBA();
            ProductTO productTO = productBA.GetValidAuctionProductByID(productId);
            if (productTO == null)
            {
                Attributes.Add("msg", "Product is closed! Please choose other product");
                this.isLoad = true;
                return;
            }

            if (productTO.CurrentPrice + productTO.StepPrice != price)
            {
                Attributes.Add("msg", "Information about price is changed, please auction again!");
                this.isLoad = true;
                return;
            }

            AuctionLogBA auctionBA = new AuctionLogBA();
            AuctionLogTO auctionLogTO = new AuctionLogTO();
            auctionLogTO.ProductID = productId;
            auctionLogTO.Price = price;
            auctionLogTO.BuyerID =Convert.ToInt32(userId);
            auctionLogTO.BidDate = DateTime.Now;
            auctionLogTO.Status = Constant.STATUS_KING_TEM;
            DateTime currentDate= DateTime.Now;
            auctionBA.InsertAuctionLog(auctionLogTO);
            productBA.UpdateProductByPlusMinute(productId, currentDate);
            productBA.UpdateProductByCurrentPrice(productId, price);
            Response.Redirect("/DetailProduct.aspx?id="+productId+"");
        }

        public void InsertLike(HttpRequest Request, HttpResponse Response)
        {
            if (Request["ID"] == null || Request["ID"].Equals("") || !StringUtil.IsPositiveNumber(Request["ID"]))
            {
                Attributes.Add("error", "Information is invalid");
                this.isLoad = true;
                return;
            }
            int ID =Convert.ToInt32(Request["ID"]);
            LikeDislikeBA likeBA = new LikeDislikeBA();
            LikeDislikeTO likeTO = new LikeDislikeTO();
            likeTO.ProductID = ID;
            likeTO.CustomerID = (int)Session["USER_ID"];
            likeTO.LikeDislike = Constant.LIKE;
            likeBA.InsertLikeDislike(likeTO);
            this.isLoad = true;
        }
    }
}